package com.jlf.starter.redis.reactive;

import lombok.Getter;
import lombok.Setter;
import org.reactivestreams.Publisher;
import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.lang.NonNull;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;

/**
 * 定义值的缓存处理
 *
 * @author wujr
 * 2023/8/4
 * @version 1.0
 * 【变更历史】
 * [wujr 2023/8/4 1.0 新增]
 */
@Getter
@Setter
public class CustomReactiveRedisTemplate<K, V> extends ReactiveRedisTemplate<K, V> {
    /**
     * 是否禁用删除指令
     */
    private boolean forbidDeleteCommand = true;

    public CustomReactiveRedisTemplate(ReactiveRedisConnectionFactory connectionFactory, RedisSerializationContext<K, V> serializationContext) {
        super(connectionFactory, serializationContext);
    }

    public CustomReactiveRedisTemplate(ReactiveRedisConnectionFactory connectionFactory, RedisSerializationContext<K, V> serializationContext, boolean exposeConnection) {
        super(connectionFactory, serializationContext, exposeConnection);
    }

    @Override
    @NonNull
    public Mono<Long> delete(@NonNull Publisher<K> keys) {
        if (forbidDeleteCommand){
            // 删除指令被禁用了
            Duration d = Duration.ofMillis(1L);
            return Flux.from(keys).map(k -> super.expire(k, d)).count();
        }else{
            return super.delete(keys);
        }
    }
}
